# -*- coding: utf-8 -*-
"""
  @Time    : 2023/2/28 15:51
  @Author  : 
  @email   : 
  @File    : app.py
"""

from flask import Flask, render_template, send_from_directory
from logging.handlers import RotatingFileHandler
from route.home import home_bp
from route.containers import containers_bp
from route.system import system_bp
from route.task import task_bp
from task.manage import register_jobs
from extensions import scheduler
import setting
import json
import logging
import os

# Flask实例化
app = Flask(__name__, template_folder='templates')


# 加载配置文件
app.config.from_object(setting.BaseConfig)
app.config.from_object(setting.APSchedulerJobConfig)
app.config.from_file(app.config.get('APP_CONFIG'), load=json.load)
app.config['BASE_DIR'] = os.path.dirname(os.path.abspath(__file__))


# 注册蓝图
app.register_blueprint(home_bp)
app.register_blueprint(containers_bp)
app.register_blueprint(system_bp)
app.register_blueprint(task_bp)


# 配置日志
try:
    max_bytes = app.config.get('LOG_MAX_BYTES')
    backup_count = app.config.get('LOG_BACKUP_COUNT')
except Exception as e:
    max_bytes = 102400000
    backup_count = 5

log_handler = RotatingFileHandler(
    filename=os.path.join(app.config['BASE_DIR'], 'log/server.log'),
    maxBytes=max_bytes,
    backupCount=backup_count)
log_handler.setFormatter(logging.Formatter(
    "[%(asctime)s-%(filename)s-%(levelname)s]: %(message)s"))

app.logger.setLevel(logging.INFO)
app.logger.addHandler(log_handler)


if __name__ == '__main__':
    scheduler.init_app(app)
    scheduler.start()
    register_jobs()
    app.run(
        debug=app.config.get('DEBUG'),
        host=app.config.get('HOST'),
        port=app.config.get('PORT'))
